package com.lxq.market.servlet;

import com.lxq.market.util.Defined;

import javax.servlet.ServletContext;
import javax.servlet.ServletOutputStream;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.net.URLDecoder;
import java.net.URLEncoder;

@WebServlet(urlPatterns = Defined.urlMap+"/*")
public class ExternalServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse res) throws IOException {
        String requestURL = String.valueOf(req.getRequestURL());
        requestURL=URLDecoder.decode(String.valueOf(requestURL), "utf-8");
        String resourcePath = requestURL.substring(requestURL.indexOf(Defined.urlMap)).replace(Defined.urlMap, Defined.external);
        File resourceFile=new File(resourcePath);
        if (!resourceFile.exists()||!resourceFile.isFile()){
            res.setStatus(HttpServletResponse.SC_NOT_FOUND);
            return;
        }
        ServletContext servletContext=req.getServletContext();
        String fileType=requestURL.substring(requestURL.lastIndexOf(".")+1).toLowerCase();
        String resourceFileName = resourceFile.getName().replace("."+fileType,"");
        BufferedInputStream bufferedInputStream=new BufferedInputStream(new FileInputStream(resourceFile));
        byte[] transferBytes=new byte[1024];
        ServletOutputStream outputStream = res.getOutputStream();
        int len;
        do {
            len = bufferedInputStream.read(transferBytes);
            outputStream.write(transferBytes,0,len);
        } while (len != -1);
        switch (fileType){
            case "apk":
                res.setHeader("Content-Disposition","attachment;filename="+ URLEncoder.encode(resourceFileName+"."+fileType
                        ,"UTF-8") );
                break;
            case "jpg": case "jpeg": case "gif": case "png": default:
                String mimeType = servletContext.getMimeType(resourceFileName + "." + fileType);
                res.setContentType(mimeType);
                break;
        }
        res.setContentLengthLong(resourceFile.length());
        outputStream.flush();
        bufferedInputStream.close();
    }
}
